package com.config.security;

import com.common.Result;
import com.common.ResultEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当接口没有权限时，自定义返回结果
 * @author Clay
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        System.out.println("???");
        Result fail = Result.fail(ResultEnum.FORBID.getCode(), "权限不足, 请联系管理员!");
        writer.write(new ObjectMapper().writeValueAsString(fail));
        writer.flush();
        writer.close();
    }
}
